package com.hispeed.management.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * JsonUtil
 * Jackson Json工具类
 * @author zhangzb
 * @date 2017-5-10
 */
public class JsonUtil {

	private static ObjectMapper objectMapper = new ObjectMapper();
	private static JsonFactory jsonFactory = new JsonFactory();


	/**
	 * 泛型返回，json字符串转对象
	 * @param jsonAsString
	 * @param pojoClass
	 * @param <T>
	 * @return
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @throws IOException
	 */
	public static <T> T fromJson(String jsonAsString, Class<T> pojoClass)
			throws JsonMappingException, JsonParseException, IOException {
		return objectMapper.readValue(jsonAsString, pojoClass);
	}

	/**
	 * Object对象转json
	 * @param object
	 * @return
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 * @throws IOException
	 */
	public static String toJson(Object object) throws JsonMappingException, JsonGenerationException, IOException {
		return toJson(object, false);
	}

	/**
	 * json字符串转Map
	 * @param jsonStr
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Object> toMap(String jsonStr) throws IOException {
		Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);
		return map;
	}

	/**
	 * Json字符串转List对象
	 * @param jsonStr
	 * @param clazz
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public static <T> List<T> toList(String jsonStr,Class<T> clazz) throws IOException {
		JavaType javaType = getCollectionType(ArrayList.class, clazz);
		return (List<T>)objectMapper.readValue(jsonStr, javaType);
	}

	private static String toJson(Object object, boolean prettyPrint)
			throws JsonMappingException, JsonGenerationException, IOException {
		StringWriter sw = new StringWriter();
		JsonGenerator jg = jsonFactory.createJsonGenerator(sw);
		if (prettyPrint) {
			jg.useDefaultPrettyPrinter();
		}
		objectMapper.writeValue(jg, object);
		return sw.toString();
	}

	/**
	 * 获取泛型的Collection Type
	 * @param collectionClass 泛型的Collection
	 * @param elementClasses 元素类
	 * @return Java类型
	 */
	private static JavaType getCollectionType(Class<?> collectionClass,
                                              Class<?>... elementClasses) {
		return objectMapper.getTypeFactory().constructParametricType(
				collectionClass, elementClasses);
	}
}
